package cn.deschen.eshop.auth.filter;

import cn.hutool.core.collection.CollUtil;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Author hanbin_chen
 * @Description 动态权限决策管理器，用于判断用户是否有访问权限
 * @DateTime 2021/1/21 16:14
 * @Version V1.0.0
 */
@Component
public class DynamicAccessDecisionManager implements AccessDecisionManager {

    /**
     * 访问的多个权限中，只要有一个符合用户的权限则校验通过
     * @param authentication 用户信息（包含所含权限）
     * @param object FilterInvocation对象，可以得到request等web资源。
     * @param configAttributes 访问路径对应的权限
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        // 当接口未被配置资源时直接放行
        if (CollUtil.isEmpty(configAttributes)) {
            return;
        }
        // 遍历该访问路径权限，判断该用户是否有该权限
        for (ConfigAttribute attribute : configAttributes) {
            String needAuthority = attribute.getAttribute();
            // 遍历用户拥有权限，与访问所需权限比较
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                if (needAuthority.equals(authority.getAuthority())) {
                    return;
                }
            }
        }
        // 该用户没有访问权限
        throw new AccessDeniedException("抱歉，您没有访问权限");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
